<template>
  <div>
    <el-form :model="editCateForm" :rules="editCateFormRules" ref="addCateFormRef" label-width="100px">
      <el-form-item label="分类名称" prop="cat_name">
        <el-input v-model="editCateForm.cat_name"></el-input>
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="editCate">确 定</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: [
    'id'
  ],
  data() {
    return {
        editCateForm: {
          cat_name: ''
        },
        // 修改分类表单的验证规则
        editCateFormRules: {
          cat_name: [
            { required: true, message: '请输入分类名称', trigger: 'blur' }
            ]
        },
        goodsid: this.id
    }
  },
  created() {
    // this.getParentCateList()
    this.sendRefs()
    this.send()
    this.getCategories(this.goodsid)
  },
  methods: {
    send() {
      this.$emit('changeTitle', '修改分类')
    },
    // 向父组件发送子组件的refs
    sendRefs() {
      this.$emit('refs', 'editCateRef')
    },
    // 点击取消按钮关闭对话框
    closeDialog() {
      this.$refs.addCateFormRef.resetFields()
      this.$emit('close', false)
    },
    // 点击确认按钮的事件
    editCate() {
      const that = this
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return // 预校验失败
        const { data: res } = await this.$http.put('categories/' + this.goodsid, { cat_name: that.editCateForm.cat_name })
        if (res.meta.status !== 200) {
          return this.$message.error('修改分类失败')
        }
        this.$message.success('修改分类成功')
        this.$emit('close', false)
      })
    },
    // 通过id获取商品分类的信息
    async getCategories(id) {
      this.goodsid = id
      console.log(id)
      const that = this
      const { data: res } = await this.$http.get('categories/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      that.editCateForm.cat_name = res.data.cat_name
    }
  }

}
</script>

<style>
.btn{
  float: right;
  margin-top: 15px;
}
</style>
